﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RAP.Framework.Libary.DataSource;
using RAP.Framework.Libary.Utils;

namespace RAP.Framework.Libary.SqlTaskParser.Parsers
{
  /// <summary>
  /// 结果集分页限制Token，主要是包装SQLServer2014的裹脚布语法
  /// </summary>
  public class ResultLimitTokenParser : TokenParserBase
  {
    public override void ParseToken(SqlParseContext parseContext)
    {
      var task = parseContext.CurrentTask;
      if (task == null)
      {
        return;
      }
      var token = parseContext.CurrentToken;
      var tokenParam = token.Param?.Trim();
      if (tokenParam.IsNullOrEmpty())
      {
        return;
      }
      var limitParams = tokenParam.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
      if (limitParams.IsNullOrEmpty() || limitParams.Length < 2)
      {
        throw new Exception("@limit 指令参数错误！");
      }
      var startIndex = limitParams.First();
      var pageSize = limitParams[1];
      var sqlGrammar = GetSqlGrammarOption(parseContext);
      if (sqlGrammar.IsNullOrEmpty())
      {
        return;
      }
      var limitSql = GeneratorPagingSqlText(sqlGrammar, startIndex, pageSize);
      ReplaceToken(parseContext, limitSql);
    }

    /// <summary>
    /// 生成SQLServer2012以上版本的分页语句
    /// </summary>
    /// <param name="startIndex"></param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    protected virtual string GeneratorPagingSqlText(string sqlGrammar, string startIndex, string pageSize)
    {
      switch (sqlGrammar)
      {
        case SQLGrammars.MSSQL:
          return $" offset {startIndex} rows fetch next {pageSize} rows only;";

        case SQLGrammars.MYSQL:
          return $" limit {startIndex}, {pageSize};";
      }
      return string.Empty;
      
    }
  }
}
